var VerticalGrid = new Class({

    Implements: [Options, Events],

    options: { },
    
    jQuery: 'vertical_grid',
    
    initialize: function(element, options)
    {
        this.setOptions(options);
        this.container = element;
        
        this.value = this.options.init_value;
        this.dataUrl = this.container.attr('data-url');

        this._InitGridContent();
    },

    _InitGridContent: function()
    {
        var self = this;

        this.submitButton = this.container.find('a.submit_new_record');
        this.submitButton.click(
            function(event)
            {
                self._OnSubmitNewRecordClick(event)
            });

        this.submitCurrentRecordButton = this.container.find('a.submit_current_record');
        this.submitCurrentRecordButton.click(
            function(event)
            {
                self._OnSubmitCurrentRecordClick(event)
            });
    },

    _OnSubmitNewRecordClick: function(event)
    {
        event.preventDefault();

        var form = this.container.children("form");

        form.ajaxSubmit(
        {
            url: this.submitButton.attr('data-url'),
            dataType: 'xml',
            success: function(data)
            {
                var response = $(data).find('response');
                alert(response.find('type').text());
            }
        });
    },

    _OnSubmitCurrentRecordClick: function(event)
    {
        event.preventDefault();

        var form = this.container.children("form");

        form.ajaxSubmit(
        {
            url: this.submitCurrentRecordButton.attr('data-url'),
            type: 'xml',
            success: function(data)
            {
                var response = $(data).find('response');
                alert(response.find('type').text());
            }
        });
    },

    _ReplaceContent: function(content)
    {
        var self = this;

        self.container.find('*').remove();
        self.container.append(content);

        this._InitGridContent();
    },

    UpdateGrid: function(updateOperationName, primaryKeys)
    {
        var self = this;
        
        primaryKeysData = {};
        for(var i = 0; i < primaryKeys.length; i++)
            primaryKeysData['pk' + i.toString()] = primaryKeys[0];
        
        $.get(this.dataUrl,
            $.extend({}, primaryKeysData, { 'a': 'update', 'sa': updateOperationName }),
            function(data)
            {
                var response = $(data).find('response');
                var content = $(response.find('content').text());
                self._ReplaceContent(content);
            },
            'xml'
        );
    }
});